<?php
namespace app\index\controller;
use app\common\enums\ResultEnum;
use app\common\model\AccessRole;
use app\common\model\Agency;
use app\common\model\MenuShow;
use app\common\model\Role as RoleModel;
use app\common\model\RoleShow;
use app\common\utils\ResultVOUtil;
use think\Request;
use think\facade\Log;


class Role extends Base
{
    public function index(Request $request,$page=1,$length=10){
        $data = $request->post();
        $where = [];
        
        $agency_id = session('admin.agency_id');
        if (strpos($agency_id, '1') === false) {
            
            $where[] = ['agency_id','in','1,'.$agency_id];
        }
        
        if(!empty($data['search'])){
            $where[] = ['name','like','%'.$data['search'].'%'];
        }
        
        try {
            $model = RoleModel::with('agency')->where($where)
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
            
        } catch (\Exception $e) {
            Log::record('角色表查询数据:'.$e->getMessage(),'error');
            return ResultVOUtil::error(ResultEnum::ERROR);
        }
        return ResultVOUtil::success($model);
    }
    
    /**
     * 显示资源列表
     *
     *角色编辑
     * @return \think\Response
     */
    public function edit(Request $request){
        $data = $request->param();
        if(!empty($data)){
            AccessRole::where(['role_id'=>$data['role_id']])->delete();
            RoleShow::where(['role_id'=>$data['role_id']])->delete();
            $access_id = MenuShow::where('id','in',$data['id'])->column('access_id');
            $accessString = implode(",", $access_id);
            $accessArray = explode(',',$accessString);
            
            $model = new AccessRole;
            
            $accessRolesData=[];
            foreach ($accessArray as $value) {
               $accessRolesData[] = ['role_id'=>$data['role_id'],'access_id'=>$value];
            }
            
           try {
               $int = $model->insertAll($accessRolesData);             
           } catch (\Exception $e) {
               Log::record('角色权限表插入数据:'.$e->getMessage(),'error');
               return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
           }
           
           if($int){ 
               $roleShowID = explode(',',$data['id']);
               $role_show = new RoleShow;
               $roleShowData = [];
               foreach ($roleShowID as $value){
                   $roleShowData[] = ['role_id'=>$data['role_id'],'show_id'=>$value];
               }
               
               try{
                   $role_show->insertAll($roleShowData);
               }catch (\Exception $e){
                   Log::record('权限页面展示表插入数据:'.$e->getMessage(),'error');
                   return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
               }
           }
           return ResultVOUtil::success('添加成功');
        }
    }
    
    
    /**
     * 显示资源列表
     *
     *添加角色
     * @return \think\Response
     */
    public function save(Request $request){
        $data = $request->param();
        if(!empty($data)){
          
            $model = new RoleModel;
            try {
                $model->save($data);
            } catch (\Exception $e) {
                Log::record('角色表插入数据:'.$e->getMessage(),'error');
                return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
            }
            return ResultVOUtil::success('添加成功');  
        }
    }
    
    /**
     * 显示资源列表
     * 
     * 编辑页面展示
     * @return \think\Response
     */
    public function show($role_id){
        $rolesMenu = RoleShow::where(['role_id'=>$role_id])->column('show_id');
        $menu = MenuShow::where(['pid'=>0])->select();
        $datum = [];
        
        foreach ($menu as $key => $value) {
            $element = MenuShow::where(['pid'=>$value['id']])->select();
            if(in_array($value['id'], $rolesMenu)){
                try {
                    $childrenId =  array_column($element->toArray(),'id');
                    $interChild = array_intersect($rolesMenu,$childrenId);

                    if(count($interChild) == count($element)){
                        $value['indeterminate'] = false;
                        $value['checked'] = true;
                    }else{
                        $value['indeterminate'] = true;
                        $value['checked'] = false;
                    }
                    
                } catch (\Exception $e) {
                    Log::record('[展示权限菜单]:'.$e->getMessage(),'error');
                    return ResultVOUtil::error(ResultEnum::FIND_ERROR);
                }
               
            }else{
                $value['indeterminate'] = false;
                $value['checked'] = false;
            }
            $datum[$key] = $value;
            $datum[$key]['children'] = $element;
        } 
        
        return ResultVOUtil::success(['rolesMenu'=>$rolesMenu,'datum'=>$datum]);
        
    }
    
    
    /**
     * 显示资源列表
     *
     *角色添加展示类型
     * @return \think\Response
     */
    public function list(){
        $data = [];
        $agency_id = session('admin.agency_id');
        if (strpos($agency_id, '1') === false) {
            $data['agency'] = Agency::where('id', 'in', '1,'.$agency_id)->select();
        } else {
            $data['agency'] = Agency::all();
        }
        return ResultVOUtil::success($data);
    }
    
}